//
//  OALoginViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "anquanwebViewController.h"

#import "xxx.h"
#import <CoreTelephony/CTCarrier.h>  
#import "OALoginViewController.h"
#import "MainViewController.h"
#import "XmlParseHelper.h"
//#import "AuthHelper.h"
//#import "sdkheader.h"
//#import "sslvpnnb.h"
#import "webViewController.h"
#import "MainTabBarController.h"
#import "MenuViewController.h"
#import "ZLCGuidePageView.h"

@interface OALoginViewController ()<UITextFieldDelegate>
{
    int firstLoginType;

}
//@property (nonatomic, strong) AuthHelper *helper;
@property(nonatomic,strong)NSArray * array;
@property(nonatomic,strong)NSDictionary * dic2;

@end

@implementation OALoginViewController
short port = 443;                        //vpn设备端口号，一般为443
//NSString *vpnIp =    vpnid;  //vpn设备IP地址
NSString *userName = @"testfz";             //用户名认证的用户名
NSString *password = @"123456";                //用户名认证的密码

NSString *certName = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd =  @"";          //证书密码，如果服务端没有设置证书

- (void)viewWillAppear:(BOOL)animated{
   

}
- (void)viewDidLoad {


    [super viewDidLoad];
    
    

//    if([[NSUserDefaults standardUserDefaults]boolForKey:@"firstStart"]){

 if(![[NSUserDefaults standardUserDefaults]boolForKey:@"firstip"]){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstip"];
//引导页图片数组
 [[NSUserDefaults standardUserDefaults] setObject:@"112.11.119.146" forKey:@"vpnid"];
}
 if(![[NSUserDefaults standardUserDefaults]boolForKey:@"firstsave"]){

_bgview0= [[UIView alloc]initWithFrame:CGRectMake(0, 0,KScreenWidth, KScreenHeight)];
_bgview0.backgroundColor = [UIColor colorWithWhite:.3 alpha:.7];
//_bgview0.alpha = 0.7;
[self.view addSubview:_bgview0];

_bgview = [[UIView alloc]initWithFrame:CGRectMake(20, 200,KScreenWidth-40, 150)];
_bgview.backgroundColor = [UIColor whiteColor];
_bgview.alpha = 1;

[_bgview0 addSubview:_bgview];
UILabel *label = [[UILabel alloc]init];
label.numberOfLines = 0;
label.frame = CGRectMake(5, 5, _bgview.width-10, 120);
label.text = @"海宁市环保局办公移动用户应重视并遵守网络信息安全等相关法律法规，承担相应信息安全责任。在使用APP前，请查阅《信息安全须知》";
[_bgview addSubview:label];
UIColor *bgcolor = self.view.tintColor;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitleColor:bgcolor forState:UIControlStateNormal];
[button setTitle:@"查看详情" forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize: 13.0];

button.frame = CGRectMake(_bgview.width-110, label.bottom,100, 20);
[button addTarget:self action:@selector(pushaction) forControlEvents:UIControlEventTouchUpInside];
[_bgview addSubview:button];
}
//}
 if(![[NSUserDefaults standardUserDefaults]boolForKey:@"firstStart"]){
//引导页图片数组

    NSArray *images =  @[[UIImage imageNamed:@"2、欢迎页面-2（640x1136）.jpg"],[UIImage imageNamed:@"2、欢迎页面-3（640x1136）.jpg"],[UIImage imageNamed:@"2、欢迎页面-1（640x1136）.jpg"]];
    //创建引导页视图
    ZLCGuidePageView *pageView = [[ZLCGuidePageView alloc]initWithFrame:self.view.frame WithImages:images];
    [self.view addSubview:pageView];

}
_rememberlabel.hidden = YES;
_rememberbutton.hidden = YES;
_autlabel.hidden = YES;
_autobutton.hidden = YES;
    self.rememberbutton.selected = YES;
        // Do any additional setup after loading the view.


// 登陆按钮
//[_buttonlayer.layer setMasksToBounds:YES];

[_buttonlayer.layer setCornerRadius:20.0];//设置矩形四个圆角半径

//[_buttonlayer.layer setBorderWidth:2.0];//边框宽度
UIColor *textColor = self.view.tintColor;

UIColor *color = [[UIColor blueColor]colorWithAlphaComponent:.7];
//_buttonlayer.layer.borderColor=textColor.CGColor;

    UIImageView *image1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"密码_icon"]];
      image1.frame = CGRectMake(10, 5, 20, 20);
    
//image1.transform = CGAffineTransformMakeTranslation(30, 0);
       //image1.contentMode = UIViewContentModeTopLeft;
   UIView *view1 = [[UIView alloc]init];
   view1.backgroundColor = [UIColor whiteColor];
   view1.size = CGSizeMake(30,30);
   [view1 addSubview:image1];
    self.passwordTextField.leftView = view1;
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
UIImageView *image2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"账号_icon"]];
 image2.frame = CGRectMake(10, 5, 15, 20);
  UIView *view2 = [[UIView alloc]init];
   view2.backgroundColor = [UIColor whiteColor];
   view2.size = CGSizeMake(30,30);
   [view2 addSubview:image2];

 
    self.accountTextField.leftView = view2;
    self.accountTextField.leftViewMode = UITextFieldViewModeAlways;

 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] length] !=0) {
        self.accountTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    }
    
    
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"] length] !=0) {
        self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"];
    }
//
//    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
//        self.autobutton.selected = YES;
//    }
     // 判断版本
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
 CFShow((__bridge CFTypeRef)(infoDictionary));
// app名称
 NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
 // app版本
_verson= [infoDictionary objectForKey:@"CFBundleShortVersionString"];
//[self _shadow];
}




- (void)_shadow{
 _accountTextField.layer.shadowOffset =  CGSizeMake(5,5);
    _accountTextField.layer.shadowOpacity = 0.75;
    _accountTextField.layer.shadowColor = [UIColor colorWithHexString:@"0436be" ].CGColor;
_accountTextField.layer.shadowRadius = 5;


}



- (void)pushaction{
anquanwebViewController *vc = [[anquanwebViewController alloc]init];
        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:vc];

        vc.navigationController.navigationBar.hidden = NO;
vc.navigationController.navigationBar.barStyle = UIStatusBarStyleDefault;
[vc setNeedsStatusBarAppearanceUpdate];
               self.view.window.rootViewController = navVC;

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setin{
[self.accountTextField resignFirstResponder];
[self.passwordTextField resignFirstResponder];
     NSString *strUrl = [self.accountTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
         strUrl = [strUrl lowercaseString];

    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:strUrl forKey:@"userId"];
     [params setObject:self.passwordTextField.text forKey:@"pwdId"];
[HttpTools postWithURL:KLoginURL arrays:@[@{@"userId":strUrl},@{@"pwdId":self.passwordTextField.text}] method:@"validationUser" success:^(id JSON) {

       [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        XmlParseHelper * parse = [[XmlParseHelper alloc]initWithData:JSON];
        NSArray * dataArray = [parse selectNodes:@"errmsg"];
        NSString * resultTag = nil;
        if (dataArray.count) {
            NSDictionary * dic  = [dataArray lastObject];
            resultTag = dic[@"text"];
        }
//         MainViewController * mainVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MainVC"];
//        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:mainVC];
    
//     MainTabBarController *tar = [[MainTabBarController alloc]init];
         MenuViewController *tar = [[MenuViewController alloc]init];

    
    
        switch ([resultTag integerValue]) {
            case 1:
                 [self.view makeToast:@"您的用户名不存在，请确认后再输"];
                break;
                case 2:

               self.view.window.rootViewController = tar;
                                   [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];

//                if (self.rememberbutton.selected) {
//                    [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
//                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];
//
//                }else{
//                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"userId"];
//                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"pwdId"];
//                }
//
//                if (!self.autobutton.selected) {
//                    [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
//                }else{
//                    [[NSUserDefaults standardUserDefaults] setObject:@"Y" forKey:@"autoLogin"];
//                }

                break;
                case 3:
                [self.view makeToast:@"您的密码错误，请确认后再输"];
                break;
                case -1099:
                [self.view makeToast:@"抱歉，服务器出错"];
                break;
            default:
                break;
        }
        
    } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
}
- (IBAction)LoginAction:(id)sender {
//if ([_type isEqualToString:@"1"]) {
//    [self setin ];
//}
//else{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

if (self.accountTextField.text.length == 0) {
        [self.view makeToast:@"请输入账号"];
        return;
    } 
    if (self.passwordTextField.text.length == 0) {
        [self.view makeToast:@"请输入密码"];
        return;
    }
else{
                  [self setin];
//         MenuViewController *tar = [[MenuViewController alloc]init];
//               self.view.window.rootViewController = tar;

////                [NSThread sleepForTimeInterval:1.0];
// if (VPN_STATUS_OK == [self.helper vpnQueryStatus]){
//                  [self setin];
//
////        statusView.text = @"vpn当前是已经登录状态，注销后才能再登录";
////        say_err("vpn当前是已经登录状态，注销后才能再登录");
//        return;
//    }else{
//
//     if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"shouquanid"] length] !=0) {
//           _shouquanid = [[NSUserDefaults standardUserDefaults] objectForKey:@"shouquanid"];
// MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//                hud.labelText = @"正在登录,请稍等";
//       self.helper = [AuthHelper getInstance];
//    SdkMode mode = EasyApp;
////    if (enableL3VPN.isOn) {
////        mode = L3VPN;
////    }
//            firstLoginType = SSL_AUTH_TYPE_PASSWORD;
//
//        [self.helper init:mode host:vpnid port:port delegate:self];
//    }else{
//UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"授权码" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    alertView1.delegate = self;
//    alertView1.alertViewStyle = UIAlertViewStylePlainTextInput;
//    UITextField * textField = [alertView1 textFieldAtIndex:0];
//    textField.placeholder = @"请输入授权码";
//    [alertView1 show];
//
//    }
//
//    }
//// self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
////    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
//
//
////}
}

}
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
// UITextField * textField = [alertView textFieldAtIndex:0];
//        if (textField.text.length == 0) {
//          [self.view makeToast:@"请输入授权码"];
//          return;
//        }
//        _shouquanid = textField.text;
//         MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//                hud.labelText = @"正在登录,请稍等";
//           self.helper = [AuthHelper getInstance];
//    SdkMode mode = EasyApp;
////    if (enableL3VPN.isOn) {
////        mode = L3VPN;
////    }
//            firstLoginType = SSL_AUTH_TYPE_PASSWORD;
//
//        [self.helper init:mode host:vpnid port:port delegate:self];
//
//
//}
//#pragma mark -
//#pragma mark SangforSDKDelegate
//- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
//{
//    switch (vpnErrno)
//    {
//        case RESULT_VPN_INIT_FAIL:
//        
////            statusView.text = @"Vpn Init failed!！！！";
////            say_err("Vpn Init failed");
//            break;
//        
//        case RESULT_VPN_AUTH_FAIL:
//        {
//            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
//            [self.helper clearAuthParam:@SET_RND_CODE_STR];
//            [self.helper vpnQueryStatus];
//             if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"shouquanid"] length] !=0) {
//             }else{
//
//                        [self.view makeToast:@"授权码有误"];
//
//            UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"授权码" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    alertView1.delegate = self;
//    alertView1.alertViewStyle = UIAlertViewStylePlainTextInput;
//    UITextField * textField = [alertView1 textFieldAtIndex:0];
//    textField.placeholder = @"请输入授权码";
//    [alertView1 show];
//    }
////            NSString *strUFT8 = [[NSString alloc] initWithUTF8String:ssl_vpn_get_err()];
////            statusView.text = [[NSString alloc] initWithFormat:@"%@,%@", @"vpn auth failed ",strUFT8];
////            say_err("vpn auth failed");
//        
////            NSRange range = [strUFT8 rangeOfString:@"psw_errorCode"];
////            if(range.location != NSNotFound){
////                NSString* info = ssl_get_password_safe_policy_prompt(get_err());//获取密码策略失败原因
////                statusView.text = info;
////            }
//            break;
//        }
//        case RESULT_VPN_INIT_SUCCESS:
//        {
////            statusView.text = @"vpn init success";
//            //显示当前sdk版本号
//            NSString *version = [self.helper getSdkVersion];
//            NSLog(@"sdk version is %@",version);
//            [self.helper setAuthParam:@AUTH_DEVICE_LANGUAGE param:@"en_US"];//zh_CN or en_US
//
//            switch (firstLoginType) {
//                case SSL_AUTH_TYPE_PASSWORD:
//                {
//                    if (![self initPswAuthParam]) {
////                        statusView.text = @"vpn init password param failed!!";
//                        return;
//                    }
//                    break;
//                }
////                case SSL_AUTH_TYPE_CERTIFICATE:
////                {
////                    if (![self initCertAuthParam]) {
////                        statusView.text = @"vpn init cert param failed!!";
////                        return;
////                    }
////                    break;
////                }
////                case SSL_AUTH_TYPE_TWFID:
////                {
////                    //session共享登录-子app only:从keychain中提取session ，并登录
////                    KeychainItemWrapper *wrapper= [[KeychainItemWrapper alloc] initWithIdentifier:@"Account Number" accessGroup:@"com.sangfor.SdkDemo"];
////                    NSData *session = [wrapper objectForKey:(id)kSecValueData];
////                    //设置认证参数
////                    ssl_set_sessionid(session.bytes, (int)session.length);
////                    break;
////                }
////                default:
////                    break;
//            }
//        
//            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        
//            [self.helper loginVpn:firstLoginType];
//        
//            break;
//        }
//
//        case RESULT_VPN_AUTH_SUCCESS:
////            statusView.text = [NSString stringWithFormat:@"start other auth:%d.", authType];
//            [self startOtherAuth:authType];
//            break;
//        case RESULT_VPN_AUTH_LOGOUT:
//            NSLog(@"Vpn logout success!");
//            break;
//        case RESULT_VPN_OTHER:
//            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
//                NSLog(@"Vpn relogin failed, maybe network error");
//            }
//            break;
//        
//        case RESULT_VPN_NONE:
//            break;
//        
//        case RESULT_VPN_L3VPN_FAIL: {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            [self.helper clearAuthParam:@SET_RND_CODE_STR];
//            NSString *strUFT8 = [[NSString alloc] initWithUTF8String:get_err()];
//           [self.view makeToast:[[NSString alloc] initWithFormat:@"%@,%@", @"l3vpn start fail ",strUFT8]];
////            say_err("l3vpn start failed");
//            break;
//        }
//        
//        default:
//            break;
//    }
//}
//-(BOOL)initCertAuthParam
//{
//
//    
//    [self.helper setAuthParam:@CERT_AUTH_SLECT_AUTH param:@"1"];
//    [self.helper setAuthParam:@ACCESS_GROUPS_SHARE_KEY param:@"com.test"];
//    return YES;
//}
//- (void) startOtherAuth:(const int)authType
//{
//    switch (authType)
//    {
//        case SSL_AUTH_TYPE_CERTIFICATE:
//        {
//            say_log("Start certificate Auth!!!");
//            [self initCertAuthParam];
//            break;
//        }
//        case SSL_AUTH_TYPE_PASSWORD:
//        {
//            say_log("Start Password Name Auth!!!");
//            [self initPswAuthParam];
//             break;
//        }
//        case SSL_AUTH_TYPE_NONE:
//        {
//            //session共享登录--主程序only：登录成功之后读取session，然后将它保存到keychain
//        
//            /*
//             char buffer[64];
//             int sessionLen = ssl_get_sessionid(buffer, 64);
//             NSData *data = [NSData dataWithBytes:buffer length:sessionLen];
//             KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Account Number" accessGroup:@"com.sangfor.SdkDemo"];
//             [wrapper setObject:data forKey:(id)kSecValueData];
//             */
//
//   [[NSUserDefaults standardUserDefaults] setObject:_shouquanid forKey:@"shouquanid"];
//
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            say_log("Vpn Auth success!");
////            statusView.text = @"vpn Auth success";
//[self setin];
////            [self performSelectorOnMainThread:@selector(loginSuccessAction) withObject:nil waitUntilDone:NO];
////            [self saveUserConf];
//        
//            return;
//        }
//        case SSL_AUTH_TYPE_SMS:
//        {
//            NSString *phoneNumber = [self.helper getSmsPhoneNumber];//发送手机号
//            NSString *countdown = [self.helper getSmsCountDown];//发送间隔时间（vpn服务器上配置的）,可用于做定时器，比如多少时间后可以重新获取短信。
//            NSLog(@"phone number is %@",phoneNumber);
//            NSLog(@"coundown  is %@",countdown);
////            statusView.text = [[NSString alloc] initWithFormat:@"phone number is %@, coundown  is %@", phoneNumber, countdown];
//        }
//        case SSL_AUTH_TYPE_RADIUS:
//        {
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            return;
//        }
//        case SSL_AUTH_TYPE_TOKEN: {
////            NSString *token = codeTF.text;
////            [self.helper setAuthParam:@"Token.Auth.Code" param:token];
//        } break;
//        default:
//            say_log("Other failed!!!");
//            return;
//    }
//    [self.helper loginVpn:authType];
//}
//
//-(BOOL)initPswAuthParam
//{
//
//NSString *number = [xxx myNumber ];
//    NSString *username = _shouquanid;
//    NSString *passWord = _shouquanid;
//    
//    if (!username || username.length == 0) {
//        return NO;
//    }
//    
//    [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:username];
//    [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:passWord];
//    
//    return YES;
//}
- (IBAction)IPaction:(id)sender {
 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"网络设置" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    //可以给alertview中添加一个输入框
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"例如:192.168.0.1";
    }];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"还原" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"点击了按钮1，进入按钮1的事件");
        //textFields是一个数组，获取所输入的字符串
         [[NSUserDefaults standardUserDefaults] setObject:@"112.11.119.146" forKey:@"vpnid"];

        NSLog(@"%@",alert.textFields.lastObject.text);
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"保存修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"%@",alert.textFields.lastObject.text);

             [[NSUserDefaults standardUserDefaults] setObject:alert.textFields.lastObject.text forKey:@"vpnid"];

        NSLog(@"点击了取消");
    }];
    
    [alert addAction:action2];
        [alert addAction:action1];

    [self presentViewController:alert animated:YES completion:nil];



}

- (IBAction)rememberbutton:(id)sender {
 self.rememberbutton.selected = !self.rememberbutton.selected;
    if (!self.rememberbutton.selected) {
        self.autobutton.selected = self.rememberbutton.selected;
    }
    

}

- (IBAction)autonbutton:(id)sender {
    self.autobutton.selected = !self.autobutton.selected;


//在此实现不打勾时的方法
}
@end
